<template>
  <el-form
    :inline="true"
    :model="formInline"
    style="margin-top: 40px; margin-left: 40px"
    class="demo-form-inline"
    ref="accidentForm"
  >
    <el-form-item label="Title:">
      <el-input
        v-model="formInline.title"
        placeholder="input title"
        clearable
        style="width: 160px"
      />
    </el-form-item>
    <el-form-item label="Chemical:">
      <el-select
        v-model="formInline.chemical_id"
        filterable
        clearable
        placeholder="please select chemical"
        style="width: 160px"
      >
        <el-option
          v-for="item in chemicals"
          :key="item.Id"
          :label="item.Name"
          :value="item.Id"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="Equipment:">
      <el-select
        v-model="formInline.equipment_id"
        filterable
        clearable
        placeholder="please select equipment"
        style="width: 160px"
      >
        <el-option
          v-for="item in equipments"
          :key="item.Id"
          :label="item.Name"
          :value="item.Id"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="Consumable:">
      <el-select
        v-model="formInline.consumable_id"
        filterable
        clearable
        placeholder="please select consumable"
        style="width: 160px"
      >
        <el-option
          v-for="item in consumables"
          :key="item.Id"
          :label="item.Name"
          :value="item.Id"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="Season:">
      <el-select
        v-model="formInline.season"
        placeholder="select season"
        clearable
        style="width: 160px"
      >
        <el-option label="spring" value="1" />
        <el-option label="summer" value="2" />
        <el-option label="autumn" value="3" />
        <el-option label="winter" value="4" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="Query"> Query</el-button>
      <el-button @click="Reset"> Reset </el-button>
    </el-form-item>
  </el-form>
  <el-form-item style="margin-left: 40px">
    <el-button type="primary" @click="create">Create</el-button>
    <el-button type="danger" @click="batchDelete">Delete</el-button>
  </el-form-item>
  <el-table
    :data="tableData"
    stripe
    head-align="center"
    :cell-style="{ textAlign: 'center' }"
    :header-cell-style="{ 'text-align': 'center' }"
    style="margin-left: 20px; width: calc(100% - 40px)"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column prop="Title" label="Title" width="240" />
    <el-table-column prop="TitleEn" label="TitleEn" width="240" />
    <el-table-column prop="Year" label="Year" width="60" />
    <el-table-column prop="Location" label="Location" width="200" />
    <!-- <el-table-column
      prop="ExperimentalProject"
      label="ExperimentalProject"
      width="180"
    /> -->
    <el-table-column prop="Dead" label="Dead" width="60" />
    <el-table-column prop="Injure" label="Injure" width="80" />
    <!-- <el-table-column prop="AccidentType" label="AccidentType" width="110" /> -->
    <el-table-column prop="Degree" label="Degree" width="150" />
    <!-- <el-table-column prop="Equipment" label="Equipment" width="180" /> -->
    <!-- <el-table-column prop="Chemical" label="Chemical" width="180" /> -->
    <el-table-column prop="Season" label="Season" width="120">
      <template #default="scope">
        <i v-if="scope.row.Season === '1'">Spring</i>
        <i v-if="scope.row.Season === '2'">Summer</i>
        <i v-if="scope.row.Season === '3'">Autumn</i>
        <i v-if="scope.row.Season === '4'">winter</i>
      </template>
    </el-table-column>
    <el-table-column prop="Description" label="Description" width="320" />
    <el-table-column prop="DescriptionEn" label="DescriptionEn" width="320" />
    <el-table-column label="Chemical" width="160">
      <template #default="{ row }">
        <el-button size="small" @click="showTransfer(row, '1')">
          Related chemical
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="Equipment" width="160">
      <template #default="{ row }">
        <el-button size="small" @click="showTransfer(row, '2')">
          Related equipment
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="Consumable" width="160">
      <template #default="{ row }">
        <el-button size="small" @click="showTransfer(row, '3')">
          Related consumable
        </el-button>
      </template>
    </el-table-column>
    <el-table-column label="Operation" width="180" fixed="right">
      <template #default="{ row }">
        <el-button type="primary" size="small" @click="showDialog(row, false)">
          View all related items
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 浮动表单 -->
  <div class="floating-form" v-if="showForm" fixed="right">
    <div class="form-content">
      <CreateAccident v-model="showForm" />
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" center>
    <div class="container">
      <div class="column">
        <div class="header">Chemicals</div>
        <div
          class="item"
          v-for="(item, index) in relatedItems.Chemicals"
          :key="index"
        >
          {{ item }}
        </div>
      </div>
      <div class="column">
        <div class="header">Equipments</div>
        <div
          class="item"
          v-for="(item, index) in relatedItems.Equipments"
          :key="index"
        >
          {{ item }}
        </div>
      </div>
      <div class="column">
        <div class="header">Consumables</div>
        <div
          class="item"
          v-for="(item, index) in relatedItems.Consumables"
          :key="index"
        >
          {{ item }}
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="closeDialog"> Close </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="transferVisiable"
    title="View / Edit Accident Related Items"
    width="900"
    center
  >
    <Transfer :row="selectedRow" :itemType="itemType" @close="handleClose" />
  </el-dialog>
</template>

<script setup lang="ts" name="Accident">
import { reactive, ref, onMounted } from "vue";
import api from "@/utils/axiosInstance";
import CreateAccident from "./CreateAccident.vue";
import { ElMessage } from "element-plus";
import Transfer from "./Transfer.vue";

let showForm = ref(false);
let accidentLoading = ref(false);
let tableData = ref([]);
let relatedItems = ref({
  Chemicals: Array,
  Equipments: Array,
  Consumables: Array,
});
let dialogVisible = ref(false);
let dialogTitle = ref();

// transfer
let transferVisiable = ref(false);
let selectedRow = ref();
let itemType = ref("");

// 监听选择
interface TableItem {
  Id: string; // 注意大小写，根据你的实际数据结构调整
  // 其他属性...
}
const selectable = (row: any) => ![1, 2].includes(row.Id);
let deleteIds = ref<string[]>([]);
function handleSelectionChange(val: TableItem[]) {
  for (let i = 0; i < val.length; i++) {
    deleteIds.value.push(val[i].Id);
  }
}

let formInline = reactive({
  title: "",
  chemical_id: "",
  equipment_id: "",
  consumable_id: "",
  season: "",
});

let chemicals = ref([] as any[]);
let consumables = ref([] as any[]);
let equipments = ref([] as any[]);
// 在组件挂载后发起请求
onMounted(async () => {
  try {
    // 发起 GET 请求
    const chemicalResponse = await api.post("/chemical/select");
    const consumableResponse = await api.post("/consumable/select");
    const equipmentResponse = await api.post("/equipment/select");
    // 将响应数据赋值
    chemicals.value = chemicalResponse.data;
    consumables.value = consumableResponse.data;
    equipments.value = equipmentResponse.data;
  } catch (err) {
    // 捕获错误并赋值给 error
  } finally {
    // 请求完成，将 loading 状态设置为 false
    // loading.value = false;
  }
});

onMounted(() => {
  Query();
});

const Query = () => {
  api
    .post("/accident/query", formInline)
    .then((response) => {
      // 处理API响应
      tableData.value = response.data;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
      ElMessage({
        message: "Failed to query accident record!",
        type: "error",
      });
    });
};

function Reset() {
  formInline.title = "";
  formInline.chemical_id = "";
  formInline.equipment_id = "";
  formInline.consumable_id = "";
  formInline.season = "";
  api
    .post("/accident/query", {})
    .then((response) => {
      // 处理API响应
      console.log(response.data, "response");
      tableData.value = response.data;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
      ElMessage({
        message: "Failed to query accident record!",
        type: "error",
      });
    });
  console.log(tableData, "@@@");
}

function create() {
  showForm.value = true;
}

function showDialog(row: any, value: boolean) {
  dialogTitle.value = row.TitleEn + "'s Related Items";
  api
    .post("/accident/related-item", { accident_id: row.Id })
    .then((response) => {
      console.log(response.data, "data");
      relatedItems.value = response.data;
      dialogVisible.value = true;
    })
    .catch((error) => {
      // 处理错误
      console.log(error, "error");
      ElMessage({
        message: "Failed to query accident related items!",
        type: "error",
      });
    })
    .finally(() => {});
}

function closeDialog() {
  dialogVisible.value = false;
}

function showTransfer(row: any, type: string) {
  itemType.value = type;
  transferVisiable.value = true;
  selectedRow.value = row;
  // console.log(selectedRow.value, "selectedrow");
}

// 处理子组件的关闭事件
const handleClose = () => {
  transferVisiable.value = false; // 隐藏Transfer组件
  console.log("子组件已关闭");
};

function batchDelete() {
  console.log("submit!");
  accidentLoading.value = true;

  api
    .post("/accident/delete", { ids: deleteIds.value })
    .then((response) => {
      if (response.status == 200) {
        ElMessage({
          message: "Successfully deleted selected accident record!",
          type: "success",
        });
      } else {
        ElMessage({
          message: "Failed to delete selected accident record!",
          type: "error",
        });
      }
    })
    .catch((error) => {
      // 处理错误
      ElMessage({
        message: "Failed to delete selected accident record",
        type: "error",
      });
      console.log(error, "error");
    })
    .finally(() => {
      accidentLoading.value = false;
      deleteIds.value = [];
      Query();
    });
}
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 150px;
}
.demo-form-inline .el-select {
  --el-select-width: 150px;
}
.demo-form-inline .el-date-picker {
  --el-select-width: 150px;
}

.floating-form {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.form-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 720px;
  height: 840px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.container {
  display: flex;
  border: 1px solid #ddd;
}
.column {
  flex: 1;
  border-right: 1px solid #ddd;
}
.column:last-child {
  border-right: none;
}
.header {
  padding: 10px;
  background: #f5f7fa;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
}
.item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}
.item:last-child {
  border-bottom: none;
}
</style>
